package config

import (
	"encoding/json"
	"os"
	"path/filepath"
)

// Config represents the application configuration
type Config struct {
	MaxThreads    int    `json:"max_threads"`
	DefaultOutput string `json:"default_output"`
	GlobalProxy   string `json:"global_proxy"`
	SpeedLimit    string `json:"speed_limit"`
	RetryAttempts int    `json:"retry_attempts"`
	UserAgent     string `json:"user_agent"`
}

// DefaultConfig returns the default configuration
func DefaultConfig() *Config {
	return &Config{
		MaxThreads:    4,
		DefaultOutput: "download",
		RetryAttempts: 3,
		UserAgent:     "Universal-Downloader/1.0",
	}
}

// LoadConfig loads the configuration from a file
func LoadConfig(path string) (*Config, error) {
	// If config file doesn't exist, create default
	if _, err := os.Stat(path); os.IsNotExist(err) {
		return createDefaultConfig(path)
	}

	data, err := os.ReadFile(path)
	if err != nil {
		return nil, err
	}

	var config Config
	if err := json.Unmarshal(data, &config); err != nil {
		return nil, err
	}

	return &config, nil
}

// SaveConfig saves the configuration to a file
func SaveConfig(config *Config, path string) error {
	data, err := json.MarshalIndent(config, "", "  ")
	if err != nil {
		return err
	}

	if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
		return err
	}

	return os.WriteFile(path, data, 0644)
}

// createDefaultConfig creates and saves a default configuration
func createDefaultConfig(path string) (*Config, error) {
	config := DefaultConfig()
	if err := SaveConfig(config, path); err != nil {
		return nil, err
	}
	return config, nil
}

// GetConfigPath returns the default configuration file path
func GetConfigPath() string {
	configDir, err := os.UserConfigDir()
	if err != nil {
		configDir = filepath.Join(os.Getenv("HOME"), ".config")
	}
	return filepath.Join(configDir, "downloader", "config.json")
}
